package com.ruoyi.qywx.getway.entity;

import cn.hutool.core.annotation.Alias;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.common.utils.StrUtils;
import com.ruoyi.qywx.entity.ExtGroupChat;
import com.ruoyi.qywx.entity.ExtGroupChatMember;
import com.ruoyi.qywx.enums.GroupChatType;
import lombok.Getter;
import lombok.Setter;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : hcl
 * @Date : 2023/9/7 17:44
 */
@Getter
@Setter
public class QyExternalChat {
    private String chat_id;
    private String name;
    // 群主
    private String owner;
    // 群公告
    private String notice;
    @Alias("member_list")
    private List<QyExtChatMember> members;
    private List<String> admin_list;
    private Long create_time;

    public ExtGroupChat ofExtGroupChat(Long teamId) {
        ExtGroupChat chat = new ExtGroupChat();
        chat.setName(name);
        chat.setNotice(notice);
        chat.setChatStatus(GroupChatType.NORMAL.getCode());
        chat.setCreateTime(new Date(create_time * 1000));
        chat.setTeamId(teamId);
        chat.setUserId(owner);
        chat.setWxId(chat_id);
        chat.setTotal(members.size());
        return chat;
    }

    public List<ExtGroupChatMember> chatMembers(Long teamId, Long chatId) {
        if (NumberUtils.isFalse(chatId)) {
            return null;
        }
        return members.stream().map(m -> chatMember(m, teamId, chatId)).collect(Collectors.toList());
    }

    public ExtGroupChatMember chatMember(QyExtChatMember m, Long teamId, Long chatId) {
        ExtGroupChatMember member = new ExtGroupChatMember();
        member.setChatId(chatId);
        member.setTeamId(teamId);

        member.setUserId(m.getUserid());
        member.setUserType(m.getType());
        member.setName(m.getGroup_nickname());

        member.setJoinScene(m.getJoin_scene());
        member.setJoinTime(new Date(m.getJoin_time() * 1000));

        member.setAdminType(m.getUserid().equals(owner) ? 2
                : (admin_list.contains(m.getUserid()) ? 1 : 0));

        member.setMsgArchive(false);
        member.setIsDelete(false);
        member.setExitTime(DateUtils.DATE_1970);
        member.setState(StrUtils.defaultString(m.getState(), StrUtils.EMPTY));
        return member;
    }

}
